package cn.tanghom.app.workflow.service;

import java.util.HashMap;
import java.util.Map;

import org.flowable.engine.IdentityService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.tanghom.app.system.model.User;
import cn.tanghom.support.db.ActiveRecordDao;




@Service
public class FlowableIdentifyServiceImpl implements IFlowableBaseService {

	private static final Logger logger = Logger.getLogger(FlowableIdentifyServiceImpl.class);

	@Autowired
	protected ActiveRecordDao jdbcDao;
	
	@Autowired
	protected IdentityService identityService;
	
	@Override
	public void deleteAllUser() {
		String sql = "ACT_ID_USER";
		this.jdbcDao.delete(sql, null);
		logger.debug("deleted from activiti user.");
	}

	@Override
	public void deleteAllRole() {
		String sql = "ACT_ID_GROUP";
		this.jdbcDao.delete(sql, null);
		logger.debug("deleted from activiti group.");
	}

	@Override
	public void deleteAllMemerShip() {
		String sql = "ACT_ID_MEMBERSHIP";
		this.jdbcDao.delete(sql, null);
		logger.debug("deleted from activiti membership.");
	}

	@Override
	public void addMembership(String userId, String groupId) {
		String sql = "insert into ACT_ID_MEMBERSHIP(GROUP_ID_,USER_ID_) values(:groupId,:userId)";
		Map<String, Object> paramMap = new HashMap<String, Object>();  
	    paramMap.put("groupId", groupId);  
	    paramMap.put("userId", userId);  
		this.jdbcDao.execute(sql, paramMap);
		logger.debug("update ACT_ID_MEMBERSHIP.");
		
	}
	
	 /**
     * 添加一个用户到Flowable {@link org.flowable.engine.identity.User}
     * @param user  用户对象, {@link User}
     */
    public void saveFlowableUser(User user) {
        String userId = user.getLoginName();
        org.flowable.idm.api.User activitiUser = identityService.newUser(userId);
        cloneAndSaveFlowableUser(user, activitiUser);
        logger.info("add activiti user: {}"+activitiUser);
    }
    
    

    /**
     * 使用系统用户对象属性设置到Flowable User对象中
     * @param user          系统用户对象
     * @param activitiUser  Flowable User
     */
    private void cloneAndSaveFlowableUser(User user, org.flowable.idm.api.User activitiUser) {
        activitiUser.setFirstName(user.getUserName());
        activitiUser.setLastName(user.getDescription());
        activitiUser.setPassword(user.getLoginPwd());
        activitiUser.setEmail(user.getEmail());
       
        identityService.saveUser(activitiUser);
    }
    

}
